﻿using System.Collections.ObjectModel;
using DataLayer;
using DataLayer.Repo;
using StructureMap;

namespace ViewModel
{
    public class ListViewModel<T> : WorkspaceViewModel
    {

        protected ObservableCollection<T> listItems;

        public ListViewModel()
        {
            ObjectFactory.GetInstance<IRepository<T>>().DataChanged += ListViewModel_DataChanged;
        }

        void ListViewModel_DataChanged(object sender, RepositoryDataChangedArgs<T> e)
        {
            foreach (T obj in e.Objects)
            {
                UpdateData(obj, e.DataChangeType);
            }
        }

        private void UpdateData(T item, DataChangeType changeType)
        {
            switch (changeType)
            {
                case DataChangeType.Added:
                    listItems.Add(item);
                    break;
                case DataChangeType.Removed:
                    listItems.Remove(item);    
                    break;
                case DataChangeType.Updated:
                    listItems[listItems.IndexOf(item)] = item;
                    break;
                default:
                    //do nothing
                    break;
            }
        }

        public ObservableCollection<T> ListItems
        {
            get 
            {
                if (listItems == null)
                {
                    FetchData();
                }
                return listItems;
            }
        }

        protected void FetchData()
        {
            listItems = new ObservableCollection<T>(ObjectFactory.GetInstance<IRepository<T>>().FindAll());
        }


        public void DeleteItem(T item)
        {
            ObjectFactory.GetInstance<IRepository<T>>().Remove(item);
        }
    }
}
